﻿// ********************************************
// ClassName  ：  {filename}
// Author        ：  
// Company     ： 智测心控
// Version        ：V1.0
// CreateTime ： {date}
// Description ：  
// ********************************************

using DAL.DB;
using DAL.Model;
using DataCenter;
using Newtonsoft.Json;
using System;
using System.Linq;

namespace WcfService.PatientService
{
    /// <summary>
    /// 病人服务实现类
    /// </summary>
    public class PatientService : IPatientService
    {
        /// <summary>
        /// 获取最新病人信息
        /// </summary>
        /// <returns>最新病人信息</returns>
        public string LastPatInfo()
        {
            using (var db = new YFrameContext())
            {
                var lastestPatientInfo = db.PatientInfo.OrderByDescending(u => u.CreateTime).FirstOrDefault();

                if (lastestPatientInfo != null && (DcpContext.Instance.CurentPatient == null
                   || !DcpContext.Instance.CurentPatient.Id.Equals(lastestPatientInfo.Id)))
                {
                    DcpContext.Instance.CurentPatient = lastestPatientInfo;
                    DcpContext.Instance.AlarmSetting = new AlarmSettingService.AlarmSettingService().GetAlarmSettingObject();
                }

                return JsonConvert.SerializeObject(lastestPatientInfo);
            }
        }

        /// <summary>
        /// 添加病人信息
        /// </summary>
        /// <param name="str">病人信息</param>
        /// <returns>响应信息</returns>
        public string PatAdd(string str)
        {
            using (var db = new YFrameContext())
            {
                PatientInfo patInfo = JsonConvert.DeserializeObject<PatientInfo>(str);
                db.PatientInfo.Add(patInfo);

                // 病人设备关系表
                db.PatientEquipmentRelationship.Add(new PatientEquipmentRelationship()
                {
                    // 主键
                    Id = Guid.NewGuid(),

                    // 病人主键
                    PatientId = patInfo.Id,

                    // 创建人
                    Creator = patInfo.Creator,

                    // 创建时间
                    CreateTime = patInfo.CreateTime,

                    // 修改人
                    ModifiedBy = patInfo.ModifiedBy,

                    // 修改时间
                    ModifiedTime = patInfo.ModifiedTime,
                });

                var result = db.SaveChanges();

                var json = new
                {
                    isTrue = result >= 0,
                    msg = result >= 0 ? "添加成功" : "添加失败",
                };

                if (json.isTrue && (DcpContext.Instance.CurentPatient == null
                    || !DcpContext.Instance.CurentPatient.Id.Equals(patInfo.Id)))
                {
                    DcpContext.Instance.CurentPatient = patInfo;
                    DcpContext.Instance.AlarmSetting = new AlarmSettingService.AlarmSettingService().GetAlarmSettingObject();
                }

                return JsonConvert.SerializeObject(json);
            }
        }

        /// <summary>
        /// PatArchive
        /// </summary>
        /// <param name="patid">patid</param>
        /// <returns>归档</returns>
        public string PatArchive(Guid patid)
        {
            using (var db = new YFrameContext())
            {
                // 获取患者信息
                var patInfo = db.PatientInfo.Single(o => o.Id.Equals(patid));

                // 归档记录基本信息
                var monitoringRecords = new MonitoringRecords()
                {
                    Id = Guid.NewGuid(),
                    PatientId = patid,
                    PatientInfo = patInfo,
                    ArchiveTime = DateTime.Now,

                    // 创建人
                    Creator = "admin",

                    // 创建时间
                    CreateTime = DateTime.Now,

                    // 修改人
                    ModifiedBy = "admin",

                    // 修改时间
                    ModifiedTime = DateTime.Now,
                };
                db.MonitoringRecords.Add(monitoringRecords);

                // 病人设备信息归档
                var relationshipArchiveInfos = db.PatientEquipmentRelationship.Where(o => o.PatientId.Equals(patid)).ToList();

                foreach (var item in relationshipArchiveInfos)
                {
                    db.PatientEquipmentRelationshipArchive.Add(new PatientEquipmentRelationshipArchive()
                    {
                        // 主键
                        Id = Guid.NewGuid(),

                        // 归档记录ID
                        MonitoringRecordId = monitoringRecords.Id,

                        // 病人主键
                        PatientId = item.PatientId,

                        // 一体机MAC地址
                        LocalMacAddress = item.LocalMacAddress,

                        // 蓝牙MAC地址
                        BluetoothMacAddress = item.BluetoothMacAddress,

                        // 创建人
                        Creator = item.Creator,

                        // 创建时间
                        CreateTime = DateTime.Now,

                        // 修改人
                        ModifiedBy = item.ModifiedBy,

                        // 修改时间
                        ModifiedTime = DateTime.Now,
                    });
                }

                // 事件回顾信息归档
                var eventReviewList = db.EventReview.Where(o => o.PatientId.Equals(patid) && o.MonitoringRecordId == null).ToList();
                foreach (var item in eventReviewList)
                {
                    item.MonitoringRecordId = monitoringRecords.Id;
                }

                // 无创血压记录信息归档
                var nibpRecordList = db.NibpRecord.Where(o => o.PatientId.Equals(patid) && o.MonitoringRecordId == null).ToList();
                foreach (var item in nibpRecordList)
                {
                    item.MonitoringRecordId = monitoringRecords.Id;
                }

                // 波形数据信息归档
                var waveDataList = db.WaveData.Where(o => o.PatientId.Equals(patid) && o.MonitoringRecordId == null).ToList();
                foreach (var item in waveDataList)
                {
                    item.MonitoringRecordId = monitoringRecords.Id;
                }

                // 值数据信息归档
                var valueDataList = db.ValueData.Where(o => o.PatientId.Equals(patid) && o.MonitoringRecordId == null).ToList();
                foreach (var item in valueDataList)
                {
                    item.MonitoringRecordId = monitoringRecords.Id;
                }

                var result = db.SaveChanges();

                var json = new
                {
                    isTrue = result >= 0,
                    msg = result >= 0 ? "归档成功" : "归档失败",
                };
                return JsonConvert.SerializeObject(json);
            }
        }

        /// <summary>
        /// PatSelect
        /// </summary>
        /// <param name="patId">patId</param>
        /// <returns>查询病人</returns>
        public string PatSelect(string patId)
        {
            using (var db = new YFrameContext())
            {
                var patientInfo = db.PatientInfo.AsNoTracking().FirstOrDefault(o => o.Id.ToString().Equals(patId));
                return JsonConvert.SerializeObject(patientInfo);
            }
        }

        /// <summary>
        /// PatUpda
        /// </summary>
        /// <param name="str">str</param>
        /// <returns>更新病人</returns>
        public string PatUpda(string str)
        {
            using (var db = new YFrameContext())
            {
                int result = 0;
                PatientInfo patInfo = JsonConvert.DeserializeObject<PatientInfo>(str);
                var patientInfo = db.PatientInfo.Find(patInfo.Id);
                if (patientInfo != null)
                {
                    patientInfo.PatientName = patInfo.PatientName;
                    patientInfo.Sex = patInfo.Sex;
                    patientInfo.HospitalBedNo = patInfo.HospitalBedNo;
                    patientInfo.PatientType = patInfo.PatientType;

                    result = db.SaveChanges();
                }

                var json = new
                {
                    isTrue = result >= 0,
                    msg = result >= 0 ? "修改成功" : "修改失败",
                };
                return JsonConvert.SerializeObject(json);
            }
        }
    }
}
